home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9674 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: lrz-muenchen.de!news
  2. From: watzka@stat.uni-muenchen.de (Kurt Watzka)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: malloc question
  5. Date: 12 Mar 1996 18:48:31 GMT
  6. Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
  7. Distribution: world
  8. Message-ID: <4i4gtv$fv3@sparcserver.lrz-muenchen.de>
  9. References: <4htonk$350@news.hklink.net> <4i492m$9jl@news1.warwick.net>
  10. NNTP-Posting-Host: sun2.lrz-muenchen.de
  11.  
  12. acorn@warwick.net (Peter Kohlberger) writes:
  13. >alex@station.net (Alex Chu) wrote:
  14. >>Hi everybody,
  15.  
  16. >>I have a question for the following snip C program.
  17. >>main()
  18. >>{
  19. >>  PITEM head, current;
  20. >>  head=(PITEM) malloc(sizeof(ITEM));
  21. >>            ^^^^^^^
  22. >>  head->val=1;
  23. >>}
  24.  
  25. >>I want to know why need to use the type casting PITEM in front of the
  26. >>malloc ?  Please help!
  27.  
  28. >Basically, you need the cast because head is of type "pointer to ITEM"
  29. >and malloc returns type "pointer to void".  If you try it without the
  30. >cast, your compiler will complain "cannot convert *void to *ITEM".
  31.  
  32. Only if it is not a compiler for the language defined by ISO 9899,
  33. the document that defines the C programming language.
  34.  
  35. [why is the automatic conversion from void pointer to any other
  36. pointer type not allowed in C? Well, it is allowed]
  37.  
  38. >The answer is (mostly) so that the compiler can catch your errors.
  39. >While a pointer to void can be converted to a pointer to any type of
  40. >object, it's desirable to ensure that the conversion is the actual
  41. >intent of the programmer.  
  42.  
  43. >Consider the following:
  44.  
  45. >typedef struct item1 {
  46. >  int val;
  47. >  struct item *next;
  48. >} ITEM1, *PITEM1;
  49.  
  50. >typedef struct item2 {
  51. >  int val;
  52. >  struct item *next;
  53. >  char text[40];
  54. >} ITEM2, *PITEM2;
  55.  
  56. >main()
  57. >{
  58. >  PITEM2 head2;
  59.  
  60. >  head2 =malloc(sizeof(ITEM1));     /* illegal */
  61.  
  62. This is why it is good practice to write this as 
  63.  
  64.    head2 = malloc(sizeof *head2);
  65.  
  66. for thhose of us who are worried about "dereferencing an uninitialized
  67. pointer", rest assured. The argument of operator sizeof is _not_
  68. evaluated, but it's type is taken.
  69.  
  70. >  strcpy(head2->text,"Some text for here"); 
  71.  
  72. Using head2 without checking the return value from malloc() was
  73. a bad idea since the 70s.
  74.  
  75. Kurt
  76. --
  77. | Kurt Watzka                             Phone : +49-89-2180-6254
  78. | watzka@stat.uni-muenchen.de
  79. | ua302aa@sunmail.lrz-muenchen.de
  80.